package com.dxwan.rxfit;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.dxwan.rxfit.currency.PufaHelper;
import com.dxwan.rxfit.currency.PufaService;
import com.dxwan.rxfit.currency.models.PufaResponse;
import com.dxwan.rxfit.currency.models.CurrencyItem;
import com.dxwan.rxfit.ui.fragments.CurrencyFragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, CurrencyFragment.OnListFragmentInteractionListener {

    Toolbar toolbar;

    private static final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        pufaService = new PufaHelper().getPufaService();

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show());

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        startPolling();
    }

    private void startPolling() {
     Observable.interval(0, 5, TimeUnit.SECONDS, Schedulers.io())
                .flatMapSingle(new Function<Long, SingleSource<PufaResponse>>() {
                    @Override
                    public SingleSource<PufaResponse> apply(Long aLong) throws Exception {
                        return pufaService.query(207567, "CurrencyName|MdlPrc|BuyPrc|CashBuyPrc|SellPrc|CREATE_DATE",
                                100);
                    }
                })
                .doOnError(err -> Log.e("Polling", "Error retrieving messages" + err))
                /*.onErrorResumeNext(new Function<Throwable, ObservableSource<?>>() {
                    @Override
                    public ObservableSource<?> apply(Throwable throwable) throws Exception {
                        return Single.emtpy();
                    }
                });*/
                .observeOn(AndroidSchedulers.mainThread())
             .subscribe(new Observer<PufaResponse>() {
                 @Override
                 public void onSubscribe(Disposable d) {
                 }

                 @Override
                 public void onNext(PufaResponse pufaResponse) {
                     if( pufaResponse != null){
                         if( pufaResponse.rows != null){
                             List<CurrencyItem> items = new ArrayList<>();
                             for(CurrencyItem row : pufaResponse.rows){
                                 if( !row.CurrencyName.equals("")) {

                                     row.CREATE_DATE = sdf.format( new Date());
                                     items.add(row);
                                 }
                             }
                             CurrencyFragment fragment =
                                     (CurrencyFragment)getFragmentManager().findFragmentById(R.id.currency_fragment);
                             if( fragment != null){
                                 fragment.updateData(items);
                             }
                         }
                     }
                 }

                 @Override
                 public void onError(Throwable e) {

                 }

                 @Override
                 public void onComplete() {

                 }
             });



    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
            //requestMath();
            requestData();

        } else if (id == R.id.nav_gallery) {
            ///requestGeonames();
        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void requestData() {
        mCompositeDisposable.add(pufaService.query(207567, "CurrencyName|MdlPrc|BuyPrc|CashBuyPrc|SellPrc|CREATE_DATE",
                100)
                .subscribeOn(Schedulers.io()) // "work” on io thread
                .observeOn(AndroidSchedulers.mainThread()) // "listen” on UIThread

                .subscribe(x -> {
                    Snackbar.make(toolbar, String.format("%d", x.total), Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                })
        );
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mCompositeDisposable.clear();
    }

    /*@NonNull
    private CityService mCityService;

    @NonNull
    private MathService mMathService;*/

    @NonNull
    private PufaService pufaService;



    @NonNull
    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();

    @Override
    public void onListFragmentInteraction(CurrencyItem item) {
    }

    /*private void requestMath() {
        mCompositeDisposable.add(mMathService.query("x^2-1")
                .subscribeOn(Schedulers.io()) // "work” on io thread
                .observeOn(AndroidSchedulers.mainThread()) // "listen” on UIThread

                .subscribe(x -> {
                    Snackbar.make(toolbar, x.result, Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                })
        );
    }*/

    /**
     * 由于这个api访问权限受到限制，因此废弃不用
     */
    /*@Deprecated
    private void requestGeonames() {
        mCompositeDisposable.add(mCityService.queryGeonames(44.1, -9.9, -22.4, 55.2, "de")
                .subscribeOn(Schedulers.io()) // "work” on io thread
                .observeOn(AndroidSchedulers.mainThread()) // "listen” on UIThread
                .map(new Function<CityResponse, List<Geoname>>() {
                    @Override
                    public List<Geoname> apply(
                            @io.reactivex.annotations.NonNull final CityResponse  cityResponse) throws Exception {
                        // we want to have the geonames and not the wrapper object
                        return cityResponse.geonames;
                    }
                })
                .subscribe(geonames -> displayGeonames(geonames))
        );
    }*/

    /*private void displayGeonames(List<Geoname> geonames) {

        geonames.stream().forEach( x-> Log.d("xxx", x.name));

    }*/
}
